package com.songcha.module_mine.ui.activity.browse_history

import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.library_base.mvvm.exception.NoDataException
import com.songcha.library_business.proxy.database.BookBrowseHistoryDaoManager
import com.songcha.library_business.proxy.database.BookDetailDaoManager
import com.songcha.library_business.proxy.database.BookReadProgressDaoManager
import com.songcha.module_mine.structs.BrowseHistoryItem
import io.reactivex.Observable

class BrowseHistoryRepository:BaseRepository() {
    fun getBrowseHistoryList():Observable<MutableList<BrowseHistoryItem>>{
        return Observable.create {
            val browseHistoryList= BookBrowseHistoryDaoManager.getBrowseHistoryList()
            val ids= mutableListOf<String>()
            for(item in browseHistoryList){
                ids.add(item.bookId)
            }
            val detailList= BookDetailDaoManager.getBookdetailListByIdList(ids)
            val readProgressList= BookReadProgressDaoManager.getReadProgressListByIdList(ids)
            if(detailList.size==readProgressList.size){
                val tmp= mutableListOf<BrowseHistoryItem>()
                for(i in 0 until detailList.size){
                    val detailItem=detailList[i]
                    val readProgressItem=readProgressList[i]
                    val item= BrowseHistoryItem().apply {
                        bookId=detailItem.bookId
                        author=detailItem.author
                        bookName=detailItem.name
                        thumb=detailItem.thumb
                        desc=detailItem.desc
                        textCount=detailItem.textCount
                        progress=((readProgressItem.currentChapter/(detailItem.chapterCount*1.0f))*100)
                    }

                    tmp.add(item)
                }
                it.onNext(tmp)
                it.onComplete()

            }else{
                it.onError(NoDataException())
            }
        }
    }
}